﻿using System;
using System.IO;
using System.Linq;

namespace Dexter.Storage.FileSystem {
	internal class FileSystemStorageFolder : IStorageFolder {
		private readonly string path;
		private readonly DirectoryInfo directoryInfo;

		public FileSystemStorageFolder ( string path, DirectoryInfo directoryInfo ) {
			this.path = path;
			this.directoryInfo = directoryInfo;
		}

		#region Implementation of IStorageFolder

		public string GetPath ( ) {
			return path;
		}

		public string GetName ( ) {
			return directoryInfo.Name;
		}

		public DateTime GetLastUpdated ( ) {
			return directoryInfo.LastWriteTime;
		}

		public long GetSize ( ) {
			return GetDirectorySize ( directoryInfo );
		}

		public IStorageFolder GetParent ( ) {
			if (directoryInfo.Parent != null) {
				return new FileSystemStorageFolder ( Path.GetDirectoryName ( path ), directoryInfo.Parent );
			}
			throw new ArgumentException ( string.Format ( "Directory {0} does not have a parent directory" , directoryInfo.Name ) );
		}

		#endregion

		private static bool IsHidden ( FileSystemInfo di ) {
			return ( di.Attributes & FileAttributes.Hidden ) != 0;
		}

		private static long GetDirectorySize ( DirectoryInfo directoryInfo ) {
			FileInfo[] fileInfos = directoryInfo.GetFiles ( );
			long size = fileInfos.Where ( fileInfo => !IsHidden ( fileInfo ) ).Sum ( fileInfo => fileInfo.Length );
			
			DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories ( );
			
			size += directoryInfos.Where ( dInfo => !IsHidden ( dInfo ) ).Sum ( dInfo => GetDirectorySize ( dInfo ) );

			return size;
		}
	}
}
